package com.yune.activity.download;

import android.app.AlertDialog;
import android.app.Application;
import android.content.Intent;
import android.os.Environment;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;

import com.yune.adapter.DownloadListAdapter;
import com.yune.databinding.ActivityDownloadBinding;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DownloadViewModel extends AndroidViewModel {
    private final List<String> data=new ArrayList<>();
    private DownloadListAdapter adp;
    public DownloadViewModel(@NonNull Application application) {
        super(application);
    }
    public void setBinding(ActivityDownloadBinding binding, DownloadActivity downloadActivity) {
        adp=new DownloadListAdapter(downloadActivity,data);
        binding.setAdp(adp);
        binding.downloadlistList.setOnItemLongClickListener((parent, view, position, id) -> {
            AlertDialog.Builder dia=new AlertDialog.Builder(downloadActivity);
            dia.setTitle("提示").setMessage("确认删除吗？").setPositiveButton("删除", (dialog, which) -> {
                File file=new File(Environment.getExternalStorageDirectory().getPath() + "/download/余音/"+data.get(position));
                if (file.delete()){
                    refresh();
                }
            }).setNeutralButton("取消",null).show();
            return true;
        });
        binding.downloadlistList.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent1 = new Intent();
            intent1.putExtra("cmd","newPlay");
            intent1.setAction("serviceReceiver");
            intent1.putExtra("songUrl",Environment.getExternalStorageDirectory().getPath() + "/download/余音/"+data.get(position));
            intent1.putExtra("songName",data.get(position));
            intent1.putExtra("singer","未知歌手");
            intent1.putExtra("picture","http://p3.music.126.net/92WxKsTbOeYkNB8PuA2nOg==/109951165647810950.jpg?param=200y200");
            intent1.putExtra("songId",String.valueOf(System.currentTimeMillis()));
            intent1.putExtra("fromWeb",false);
            downloadActivity.sendBroadcast(intent1);
        });
        refresh();
    }
    private void refresh() {
        data.clear();
        String[] paths=new File(Environment.getExternalStorageDirectory().getPath() + "/download/余音/").list();
        assert paths != null;
        data.addAll(Arrays.asList(paths));
        adp.notifyDataSetChanged();
    }
}
